import ArticleItem from '@/components/ArticleItem'
import NavBar from '@/components/NavBar'
import { RootState } from '@/store'
import { getSearchResult } from '@/store/action/search'
import { InfiniteScroll } from 'antd-mobile'
import { useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useLocation } from 'react-router'
import styles from './index.module.scss'

export default function SearchResult() {
  const dispatch = useDispatch()

  const { search } = useLocation()

  const searchParams = new URLSearchParams(search)

  const q = searchParams.get('q') || ''

  // useEffect(() => {
  //   dispatch(getSearchResult({ q }))
  // }, [dispatch, q])

  const { results } = useSelector((state: RootState) => state.search)

  const [hasMore, setHasMore] = useState(true)

  const page = useRef(0)

  const loadMoreFn = async () => {
    page.current = page.current + 1
    try {
      await dispatch(getSearchResult({ q, page: page.current }))
    } catch (error) {
      console.log(error)
      setHasMore(false)
    }
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} article={item} />
        ))}
        <InfiniteScroll
          hasMore={hasMore}
          loadMore={loadMoreFn}
        ></InfiniteScroll>
      </div>
    </div>
  )
}
